class LazyLoad{
    constructor(){
       this.init.call(this);
    }
    init(){
        this.m_timer = null;
        this.m_data =[]; //总数据
        this.m_extra = []; //临时数组
        this.m_cheight = document.documentElement.clientHeight;
        this.bindEvent();
    }
    bindEvent(){
        window.addEventListener("scroll",this.load.bind(this));
    }
    load(){
        if(this.m_timer !==null) return false;
        this.m_timer = setTimeout(() => {
            let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;        
            let min = scrollTop +this.m_cheight;
            for(let i = 0,item;item = this.m_data[i];i++){
                if(item.top<min){
                    item.img.src = item.src;
                    this.m_data.splice(i,1);
                    i--;
                }
            }
            this.setListData();
            this.m_timer = null;
        }, 5000);
    }
    //总数据
    setListData(){
        this.m_data = this.m_data.concat(this.m_extra);
        this.m_extra.length = 0;
    }
    //把要懒加载的DOM 放入临时数组中
    addListData(selector){
        let imgList = document.querySelectorAll(selector);
        this.m_extra = Array.from(imgList).map(item => {
            return{
                img : item,
                top : item.offsetTop,
                src : item.getAttribute("data-src")
            }
        });
        if(this.m_data.length <= 0){
            this.setListData();
        }
        this.load();
    }
}
module.exports = LazyLoad;